<template>
  <div>
    <!-- 搜索 -->
    <TopFilter
      ref="topFilter1"
      :list="topFilterInit"
      :cols="3"
      labelWidth="100"
      @filterChange="changeHandle"
      @onCollapse="collapseHandle"
    ></TopFilter>
    <!-- table -->
    <FilterTable
      ref="table"
      :columns="columns"
      :isSelectColumn="isSelectColumn"
      :fetchapi="fetchApi"
      :params="filterValue"
      :datakey="'records'"
      :onColumnsChange="columns => this.columns = columns"
      columnsRef="projectOperating_projram_distribution_index_01"
    >
      <template slot="controls">
        <el-button
          size="small"
          type="primary"
          icon="el-icon-plus"
          @click="drawerHandle(null,'add')"
        >新增</el-button>
      </template>
    </FilterTable>
    <Drawer
      :visible.sync="visibleDistributionDrawer"
      title="事业部项目方案分配"
      :width="920"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <infoDistributionModal v-model="initData" @close="drawerClose" />
    </Drawer>
    <Drawer
      :visible.sync="visibleDrawer"
      title="事业部项目方案信息"
      :width="920"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <info-modal v-model="initData" @close="drawerClose" />
    </Drawer>
    <!-- 选择车型 -->
    <BaseDialog
      title="选择车型"
      :visible.sync="visibleDialog"
      width="700px"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <!-- <typeCar   @close="closeTypeCarDialog" /> -->
      <carInfoDlg
        ref="carInfoDlg"
        selectType="single"
        :rowData2="formData2"
        @close="closeTypeCarDialog"
      />
    </BaseDialog>

    <!-- 方案明细 -->
    <Drawer
      :visible.sync="visibleDetailDrawer"
      title="方案明细"
      :width="920"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <detail v-model="initData" @close="detailClose" />
    </Drawer>
  </div>
</template>

<script>
import infoModal from './info.vue';
import infoDistributionModal from './infoDistribution.vue';
import detail from '@/pages/cms-pages/projectOperating/program/departmentInquire/detail.vue';
import typeCar from '../commonForm/infoActivityTypeCar';
import { dictionary } from '@/utils/dictMixin';
import { getRegion } from '@/api/cms-common/dealerdata/index';
import carInfoDlg from '@/pages/cms-common/product'; //car选择
import { getListProjOrg, insertProjOrg } from '@/api/cms-api/projectOperating/program/distribution';
import { getLoginUser } from '@/api/cms-api/projectOperating/program/departmentInquire';
import { formatdateByDay } from '@/utils';
export default {
  mixins: [dictionary],
  components: {
    infoModal,
    carInfoDlg,
    infoDistributionModal,
    detail
    // typeCar
  },
  data() {
    return {
      org: '',
      v_modelId: '', //车型
      arr: [],
      formData2: {}, //car
      visibleDialog: false,
      visibleDrawer: false,
      visibleDetailDrawer: false, //明细
      visibleDistributionDrawer: false, //分配
      isSelectColumn: false,
      topFilterInit: this.topFilterInitFun(),
      filterValue: {programStatus : 25281001}, //参数
      initData: {},
      formData2: {},
      formData: {},
      columns: this.creatHeader(),
      fetchApi: null, //ipa 接口
      fetchParams: getListProjOrg //ipa 接口
    };
  },

  async created() {
    // await this.getUserInfo();

    let extParams = { orgId: this.org };
    this.filterValue = Object.assign({}, this.filterValue, extParams);
    this.fetchApi = getListProjOrg;
  },
  mounted() {
    //获取事业部下拉列表
    //this.getDeptData();
    this.BaseTable = this.$refs.table.$refs.pageTable;
  },
  //方法、事件
  methods: {
    async getUserInfo() {
      this.loginUser = await getLoginUser({});
      if (this.loginUser.resultCode == 200) {
        let initList = new Array();
        let selectObj = new Object();
        selectObj.text = this.loginUser.data.orgName;
        selectObj.value = this.loginUser.data.orgId;
        initList.push(selectObj);
        this.topFilterInit[1].itemList = initList;
        this.topFilterInit[1].initialValue = this.loginUser.data.orgId;
        this.topFilterInit[1].placeholder = this.loginUser.data.orgName;
        this.org = this.loginUser.data.orgId;
      }
    },

    //获取事业部下拉列表数据
    async getDeptData() {
      const res = await getRegion();
      if (res.resultCode === 200) {
        this.topFilterInit[1].itemList = res.data.map(x => ({ value: x.orgId, text: x.orgName }));
      }
    },
    async getListProjOrgData(val) {
      this.arr = val;
      this.arr.currentPage = 1;
      this.arr.pageNum = 10;
      this.arr.pageSize = 20; //dataSource不支持分页

      const res = await getListProjOrg(this.arr);
      // debugger
      if (res.resultCode === 200) {
        var result = res.data.records;
      }
    },
    //搜索数据
    topFilterInitFun() {
      return [
        { type: 'SELECT', label: '方案下发渠道', fieldName: 'programIssuedChannel', placeholder: '请选择', initialValue: '', itemList: this.createDictList('2530') },
        { type: 'SELECT', label: '事业部', fieldName: 'orgId', placeholder: '请选择', initialValue: '', itemList: [], disabled: true },
        { type: 'SELECT', label: '方案状态', fieldName: 'programStatus', placeholder: '请选择', initialValue: 25281001, itemList: this.createDictList('2528') },
        { type: 'INPUT', label: '方案编号', fieldName: 'programCode', placeholder: '请输入', initialValue: '' },
        { type: 'INPUT', label: '方案名称', fieldName: 'programName', placeholder: '请输入', initialValue: '' },
        {
          type: 'INPUT',
          label: '车型',
          fieldName: 'modelName',
          placeholder: '请选择',
          initialValue: '',
          readonly:true,
          unitRender: () => {
            return (
                <div>
                  <el-button slot="append" icon="el-icon-search" onClick={() =>this.openModelDialog()}></el-button>
                  <el-button slot="append" icon="el-icon-delete" onClick={() => this.clearSelectModel()}></el-button>
                </div>
            );
          }
        },
        { type: 'INPUT', label: '项目名称', fieldName: 'itemName', placeholder: '请输入', initialValue: '' }
      ];
    }, //搜索获取数据
    changeHandle(val) {
      if (!val.modelName || typeof val.modelName == 'undefined' || val.modelName == '') {
        this.v_modelId = '';
      }
      let extParams = { modelId: this.v_modelId, orgId: this.org };
      this.filterValue = Object.assign({}, val, extParams);
      // val = Object.assign({}, { modelId:  this.v_modelId }, val);
      // this.filterValue = Object.assign({}, val);

      // this.getListProjOrgData(this.filterValue);
    },
    //table表头和数据源
    creatHeader() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '操作',
          dataIndex: 'column-action',
          width: 100,
          fixed: 'left',
          render: (props, h) => {
            let isOem = props.row.programIssuedChannel == '25301001' ? true : false; //根据下发渠道判断是否是厂端下发数据
            let disabled = props.row.orgStatus == '25281002' || props.row.orgStatus == '25281003 ' ? true : false; //判断是否已事业部下发
            let btnText = '编辑';
            let drawerFunc = this.drawerHandle; //事业部编辑页面（可修改，可分配、可作废）
            if (isOem) {
              btnText = '分配';
              drawerFunc = this.drawerDistributionHandle; //车厂下发方案分配页面(只可以修改经销商列表和分配)
            }
            return (
              <div>
                <el-button size="mini" type="text" disabled={disabled} onClick={() => drawerFunc(props.row, 'edit')}>
                  {btnText}
                </el-button>
                <el-divider direction="vertical" />
                <el-button size="mini" type="text" onClick={() => this.drawerDetailHandle(props.row, 'show')}>
                  明细
                </el-button>
              </div>
            );
          }
        },
        { title: '事业部', dataIndex: 'orgName', sorter: true },
        { title: '方案编号', dataIndex: 'programCode', sorter: true },
        {
          title: '方案状态',
          dataIndex: 'orgStatus',
          sorter: true,
          render: props => {
            //编码转汉字
            return <span>{this.createDictText(props.row.orgStatus, '2528')}</span>;
          }
        },
        {
          title: '方案下发渠道',
          dataIndex: 'programIssuedChannel',
          sorter: true,
          render: props => {
            //编码转汉字
            return <span>{this.createDictText(props.row.programIssuedChannel, '2530')}</span>;
          }
        },
        { title: '方案名称', dataIndex: 'programName', sorter: true },
        {
          title: '项目周期',
          dataIndex: 'projectStartDate',
          sorter: true,
          render: props => {
            return (
              <span>
                {formatdateByDay(props.row.projectStartDate)}~{formatdateByDay(props.row.projectEndDate)}
              </span>
            );
          }
        },
        { title: '创建人', dataIndex: 'createdByName', sorter: true },
        { title: '创建时间', dataIndex: 'createdAt', dateFormat: 'yyyy-MM-dd', sorter: true },
        { title: '分配人', dataIndex: 'distributionPersonName', sorter: true },
        { title: '分配时间', dataIndex: 'distributionTime', dateFormat: 'yyyy-MM-dd', sorter: true }
      ];
    },
    openModelDialog() {
      this.visibleDialog = true;
    },
    closeTypeCarDialog(data) {
      // debugger
      this.visibleDialog = false; //关闭弹窗
      this.fetchParams = { ...this.fetchParams };
      // this.$refs.topFilter1.list[5].initialValue = data.data[0].modelName; //给车型赋值
      this.topFilterInit.find(item => item.fieldName === 'modelName').initialValue= data.data[0].modelName; //给车型赋值
      this.v_modelId = data.data[0].modelId;

    },
    //清空选择车型
    clearSelectModel(){
        this.topFilterInit.find(item => item.fieldName === 'modelName').initialValue='';
        this.v_modelId = '';
    },
    //详情
    drawerHandle(row, type) {
      //逻辑自己写
      const pram = {
        type: type, //add/edit/show
        rowData: row,
        rowData2: row
      };
      this.initData = pram;
      this.formData = row;
      this.formData2 = pram;
      this.visibleDrawer = true;
    },
    //分配
    drawerDistributionHandle(row, type) {
      //逻辑自己写
      const pram = {
        type: type, //add/edit/show
        rowData: row,
        rowData2: row
      };
      this.initData = pram;
      this.formData = row;
      this.formData2 = pram;
      this.visibleDistributionDrawer = true;
    },
    //方案明细页面
    async drawerDetailHandle(row, type) {
      const pram = {
        type: type, //add/edit/show
        rowData: row,
        rowData2: row
      };
      this.initData = pram;
      this.formData = row;
      this.formData2 = pram;
      this.visibleDetailDrawer = true;
    },
    //关闭详情
    detailClose(params) {
      this.visibleDetailDrawer = false;
      if (params.refresh == true) {
        this.filterValue = { ...this.filterValue };
      }
    },
    //关闭新增修改
    drawerClose(val, type) {
      this.visibleDrawer = false;
      this.visibleDistributionDrawer = false;
      if (type === 'refresh') {
        // 重新加载
        this.filterValue = { ...this.filterValue };
      }
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    }
  }
};
</script>

<style scoped>
</style>
